from django_redis import get_redis_connection
import base64, pickle


# 实现合并购物车逻辑
def merge_good_carts(request, user, response):
    # 1获取cookie数据
    cookie_str = request.COOKIES.get('carts')
    if cookie_str:
        cookie_dict = pickle.loads(base64.b64decode(cookie_str.encode()))
    else:
        return response
    sku_dict = {}  # cookie中获取的sku_id 和count
    selected_Ture = []  # 需要勾选sku_id
    selected_False = []  # 不勾选的sku_id
    for sku_id, items in cookie_dict.items():
        sku_dict[sku_id] = items['count']
        if items['selected']:
            selected_Ture.append(sku_id)
        else:
            selected_False.append(sku_id)

    user_id = user.id
    redis_conn = get_redis_connection('carts_code')
    redis_dict = redis_conn.hgetall('carts_%s' % user_id)

    # 构建redis新字典存储新的数据，到时候重新加入到redis数据库
    redis_new_dict = {}
    for redis_sku_id, redis_count in redis_dict.items():
        redis_new_dict[int(redis_sku_id)] = int(redis_count)

    for cookie_sku_id, cookie_count in sku_dict.items():
        if cookie_sku_id in redis_new_dict.keys():
            count = cookie_count + redis_new_dict[cookie_sku_id]
            redis_new_dict[cookie_sku_id] = count
        else:
            redis_new_dict[cookie_sku_id] = cookie_count
    redis_conn.hmset('carts_%s' % user_id, redis_new_dict)

    if selected_Ture:
        redis_conn.sadd('selected_%s' % user_id, *selected_Ture)
    if selected_False:
        redis_conn.srem('selected_%s' % user_id, *selected_False)

    # 删除cookie中carts数据
    response.delete_cookie('carts')
    return response
